import {
  getImage,
  getPage,
  getTabbar,
  ChatConfig
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  storage,
  promisify,
  $toast,
  $loading,
  $query
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import {
  headerInfo
} from '../../utils/env'
const app = getApp();
let topStyle, leftStyle, tipTopStyle;

{
  let {
    height,
    right,
    menuWidth
  } = headerInfo
  console.log(headerInfo)
  leftStyle = `right: ${((menuWidth / 2) / 2) + right}px`;
  tipTopStyle = `top: ${height}px;`;
  topStyle = `top: ${height + 10}px;`;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    logged: 0,
    loading: 0,
    userId: 0,
    goodsNavFix: false,
    goodsNavType: 1,
    goodsList: [],
    pageindex: 1,
    pagesize: 0,
    loadmore: true,
    loaddone: false,
    messageList: [],
    manualStop: false,
    //  下拉刷新
    triggered: true,
    //  历史记录当前页
    pageNo: 1,
    scrollHeight: '300px',
    right: [{
      text: '删除',
    },{
        text: '删除',
        style: 'color: #fa3e3e',
    }]
  },

  /**
   * 开启
   */
  onOpen(e) {
    // console.log('eeeeeeeee=',e)
    // this.toggleSwipe(e, true);
  },
  toggleSwipe(e, t) {
    const data = e.currentTarget.dataset || e.target.dataset;
    // data(messageId index)
    const { messageList } = this.data;

    if (data.messageId !== undefined){
      messageList[data.index].isOpen = t;
      this.setData({ messageList });
    }
  },
  /**
   * 删除事件
   */
  handleDelete(e) {
    const that = this;
    const data = e.currentTarget.dataset || e.target.dataset;
    // data(messageId index)
    console.log('data=====',data)
    wx.showModal({
      cancelText: '取消',
      confirmText: '确定',
      content: '是否删除？',
      success(res) {
        if (res.confirm) {
          const messageList = that.data.messageList;
          http.post(api.default, {
            data: {
              action: 'delfriends',
              fid: data.messageId,
              userid: that.data.userId,
            }
          }).then((res) => {
            messageList.forEach((item, index) => {
              if (item.Fid == data.messageId) {
                messageList.splice(index, 1);
              }
            });
            $toast(`删除成功`, {
              icon: 'success'
            });
            that.setData({
              messageList: messageList
            })
          })
        }
      },
    })
  },

  handleNotouch() {
    return false
  },

  /**
   * 禁止手动滑动
   */
  noSwiping() {
    return false;
  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  /**
   * 消息
   */
  bindChat(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    console.log(data, 'eeeeeeeeeeeeeeeeeeeeeee')
    if (data.index) {
      wxApi.navigateTo(getPage.chat, {
        user_name: data.index.ShopName || data.index.nickname || '陌生访客',
        img: data.index.head_url,
        touserid: data.index.user_id
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    app.getLogin().then((res) => {
      const {
        user
      } = res.data;
      this.setData({
        userId: user.user_id
      })
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    })
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
    //  设置滚动区域的高度
    this.setScrollHeight()
  },

  // 获取消息列表
  getMsgList:async function(){
    let params = {
      data: {
        action: 'getfriends',
        userid: this.data.userId
      }
    }
    const res = await http.post(api.default, params, false)
    var list = res.data.data.list;
    let listRes = list.filter(f=>f.IsShow).reverse()
    this.setData({
      messageList: listRes
    })
  },

  /**
   * 页面滚动函数--监听页面滚动事件
   */
  onPageScroll(e) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    const res = await app.getLogin()
    const {
      user
    } = res.data;
    this.setData({
      userId: user.user_id
    })
    if (this.data.userId > 0){
      console.log('yonghuid',this.data.userId)
      this.getMsgList()
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===',this.getTabBar())
        this.getTabBar().setData({
          // 这里的数字对应tabbar对应的索引
          selected: 3,
          number:app.globalData.unReadMsg
        });
      }
    }
  },

  // 自定义下拉刷新
  refresh: function () {
    // 下拉的实际操作
    var pageNo = this.data.pageNo + 1
    this.setData({
      pageNo
    })
    if (this.timer) {
      clearTimeout(this.timer)
    }
    this.timer = setTimeout(() => {
      this.setData({
        triggered: false
      })
      this.getMsgList()
    }, 2000)
  },
  // 设置滚动区域的高度
  setScrollHeight: function () {
    const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
    console.log('设置滚动区域的高度', client)
    var scrollHeight = client
    this.setData({
      scrollHeight
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.userId > 0) {
      pageshare += "?pid=" + this.data.userId;
    }
    return {
      title: ``,
      imageUrl: '',
      path: pageshare,
      success: function (res) {
        console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          console.log("分享失败");
        }
      }
    }
  }
})